import { ServerMetric, Task, Alert, SystemStatus } from '../types';

const serverNames = [
  'web-server-01', 'web-server-02', 'api-server-01', 'api-server-02',
  'db-server-01', 'db-server-02', 'cache-server-01', 'cache-server-02',
  'worker-01', 'worker-02', 'worker-03', 'worker-04'
];

const regions = ['北京', '上海', '广州', '深圳'];
const clusters = ['cluster-a', 'cluster-b', 'cluster-c'];

const taskNames = [
  '系统健康检查', '日志收集分析', '性能监控', '安全扫描',
  '数据备份', '服务部署', '负载测试', '内存清理'
];

const alertMessages = [
  'CPU使用率过高', '内存使用率超过阈值', '磁盘空间不足',
  '网络连接异常', '服务响应超时', '数据库连接池满',
  '缓存命中率下降', '磁盘I/O延迟过高'
];

const generateServerMetric = (id: string): ServerMetric => {
  const cpu = Math.random() * 100;
  const memory = Math.random() * 100;
  const disk = Math.random() * 100;
  const networkIn = Math.random() * 1000;
  const networkOut = Math.random() * 1000;
  const load1m = Math.random() * 10;
  const load5m = Math.random() * 8;
  const load15m = Math.random() * 6;

  let health: ServerMetric['health'] = 'healthy';
  if (cpu > 85 || memory > 90 || load1m > 5) {
    health = 'critical';
  } else if (cpu > 70 || memory > 80 || load1m > 3) {
    health = 'warning';
  }

  return {
    id,
    name: serverNames[Math.floor(Math.random() * serverNames.length)],
    region: regions[Math.floor(Math.random() * regions.length)],
    cpu: Number(cpu.toFixed(1)),
    memory: Number(memory.toFixed(1)),
    disk: Number(disk.toFixed(1)),
    networkIn: Number(networkIn.toFixed(1)),
    networkOut: Number(networkOut.toFixed(1)),
    load1m: Number(load1m.toFixed(2)),
    load5m: Number(load5m.toFixed(2)),
    load15m: Number(load15m.toFixed(2)),
    timestamp: Date.now(),
    health
  };
};

const generateTask = (id: string): Task => {
  const statuses: Task['status'][] = ['queued', 'running', 'completed', 'failed'];
  const status = statuses[Math.floor(Math.random() * statuses.length)];

  const progress = status === 'completed' ? 100 :
                   status === 'failed' ? Math.random() * 50 :
                   status === 'running' ? 20 + Math.random() * 60 :
                   Math.random() * 20;

  const startTime = Date.now() - Math.random() * 3600000;
  const endTime = status === 'completed' || status === 'failed' ?
    startTime + Math.random() * 1800000 : undefined;

  return {
    id,
    name: taskNames[Math.floor(Math.random() * taskNames.length)],
    targetCluster: clusters[Math.floor(Math.random() * clusters.length)],
    status,
    progress: Number(progress.toFixed(0)),
    startTime,
    endTime,
    description: `${taskNames[Math.floor(Math.random() * taskNames.length)]}任务执行中`
  };
};

const generateAlert = (id: string): Alert => {
  const severities: Alert['severity'][] = ['low', 'medium', 'high', 'critical'];
  const sources = ['web-server-01', 'api-server-01', 'db-server-01', 'cache-server-01'];

  return {
    id,
    timestamp: Date.now() - Math.random() * 3600000,
    source: sources[Math.floor(Math.random() * sources.length)],
    severity: severities[Math.floor(Math.random() * severities.length)],
    message: alertMessages[Math.floor(Math.random() * alertMessages.length)],
    resolved: Math.random() > 0.7
  };
};

export const generateInitialData = () => {
  const servers: ServerMetric[] = [];
  const tasks: Task[] = [];
  const alerts: Alert[] = [];

  for (let i = 0; i < 12; i++) {
    servers.push(generateServerMetric(`server-${i + 1}`));
  }

  for (let i = 0; i < 8; i++) {
    tasks.push(generateTask(`task-${i + 1}`));
  }

  for (let i = 0; i < 15; i++) {
    alerts.push(generateAlert(`alert-${i + 1}`));
  }

  return { servers, tasks, alerts };
};

export const updateServerMetrics = (servers: ServerMetric[]): ServerMetric[] => {
  return servers.map(server => {
    const change = (Math.random() - 0.5) * 10;
    const newCpu = Math.max(0, Math.min(100, server.cpu + change));
    const newMemory = Math.max(0, Math.min(100, server.memory + change * 0.8));
    const newNetworkIn = Math.max(0, server.networkIn + (Math.random() - 0.5) * 50);
    const newNetworkOut = Math.max(0, server.networkOut + (Math.random() - 0.5) * 50);
    const newLoad1m = Math.max(0, server.load1m + (Math.random() - 0.5) * 0.5);

    let health: ServerMetric['health'] = 'healthy';
    if (newCpu > 85 || newMemory > 90 || newLoad1m > 5) {
      health = 'critical';
    } else if (newCpu > 70 || newMemory > 80 || newLoad1m > 3) {
      health = 'warning';
    }

    return {
      ...server,
      cpu: Number(newCpu.toFixed(1)),
      memory: Number(newMemory.toFixed(1)),
      networkIn: Number(newNetworkIn.toFixed(1)),
      networkOut: Number(newNetworkOut.toFixed(1)),
      load1m: Number(newLoad1m.toFixed(2)),
      load5m: Number((newLoad1m * 0.8).toFixed(2)),
      load15m: Number((newLoad1m * 0.6).toFixed(2)),
      timestamp: Date.now(),
      health
    };
  });
};

export const updateTasks = (tasks: Task[]): Task[] => {
  return tasks.map(task => {
    if (task.status === 'running') {
      const progress = Math.min(100, task.progress + Math.random() * 5);
      const status = progress >= 100 ? 'completed' : 'running';

      return {
        ...task,
        progress: Number(progress.toFixed(0)),
        status,
        endTime: progress >= 100 ? Date.now() : undefined
      };
    }

    if (task.status === 'queued' && Math.random() > 0.8) {
      return {
        ...task,
        status: 'running'
      };
    }

    return task;
  });
};

export const calculateSystemStatus = (servers: ServerMetric[]): SystemStatus => {
  const totalServers = servers.length;
  const healthyServers = servers.filter(s => s.health === 'healthy').length;
  const warningServers = servers.filter(s => s.health === 'warning').length;
  const criticalServers = servers.filter(s => s.health === 'critical').length;

  const avgCpu = servers.reduce((sum, s) => sum + s.cpu, 0) / totalServers;
  const avgMemory = servers.reduce((sum, s) => sum + s.memory, 0) / totalServers;
  const avgLoad = servers.reduce((sum, s) => sum + s.load1m, 0) / totalServers;

  const networkValues = servers.map(s => s.networkIn + s.networkOut);
  const maxNetwork = Math.max(...networkValues);
  const minNetwork = Math.min(...networkValues);
  const networkRatio = maxNetwork / minNetwork;
  const networkBalance = networkRatio > 3 ? 'skewed' : 'balanced';

  return {
    totalServers,
    healthyServers,
    warningServers,
    criticalServers,
    avgCpu: Number(avgCpu.toFixed(1)),
    avgMemory: Number(avgMemory.toFixed(1)),
    avgLoad: Number(avgLoad.toFixed(2)),
    networkBalance,
    networkRatio: Number(networkRatio.toFixed(1))
  };
};